package com.hmall.item.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import java.util.Date;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    /**
     * 查询全部商品
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public PageDTO getAll(@RequestParam("page") Integer pageNumber,
                          @RequestParam("size")Integer pageSize){
        Page<Item> page = new Page<>(pageNumber,pageSize);
        IPage<Item> pages = itemService.page(page);
        return new PageDTO(pages.getTotal(),pages.getRecords());
    }

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item getById(@PathVariable Long id){
        Item item = itemService.getById(id);
        return item;
    }

    /**
     * 新增商品
     * @param item
     */
    @PostMapping
    public void addItem(@RequestBody Item item){
        if (ObjectUtils.isEmpty(item)){
            return;
        }
        item.setCreateTime(new Date());
        itemService.save(item);
    }

    /**
     * 根据id修改商品状态
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void updateStatus(@PathVariable Long id,
                             @PathVariable Integer status){
        /*LambdaQueryWrapper<Item> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Item::getId,id);*/

        itemService.updateStatus(id,status);
    }

    /**
     * 修改商品信息
     * @param item
     */
    @PutMapping
    public void updateItem(@RequestBody Item item){
        if (ObjectUtils.isEmpty(item))return;
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String dateTime = sdf.format(new Date());
        item.setUpdateTime(new Date());
        itemService.updateById(item);
    }

    /**
     * 删除商品
     * @param id
     */
    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable Long id){
        if (ObjectUtils.isEmpty(id) || id < 0) return;
        itemService.removeById(id);
    }

    /**
     * 修改库存
     * @param itemId
     * @param num
     */
    @PutMapping("/stock/{type}/{itemId}/{num}")
    public void updateStockById(@PathVariable("itemId") Long itemId,
                            @PathVariable("type") String type,
                            @PathVariable("num") Integer num){
        itemService.updateStockById(itemId,type,num);
    }
}
